<?php
/**
 * 配置类
 */
namespace framework\core;

class Config {

	/**
	 * 全局配置
	 * @var array
	 */
	static protected $config = array();

	/**
	 * 初始化配置
	 * @param  string $basePath 项目目录
	 * @return void
	 */
    static public function init($basePath = '') {
		self::$config = [
			'DEBUG' => true,	
			'TIMEZONE' => 'PRC', 
		    'ROUTE' => ['/' => 'index/Index/index'],		    
			'DB'=> [
				'DB_TYPE' => 'MysqlPdo',
				'DB_HOST' => 'localhost',
				'DB_USER' => 'root',
				'DB_PWD' => '',
				'DB_PORT' => 3306,
				'DB_NAME' => 'cp',
				'DB_CHARSET' => 'utf8',
				'DB_PREFIX' => '',
				'DB_CACHE' => 'DB_CACHE',						
				'DB_SLAVE' => [],
				/*
				'DB_SLAVE' => [['DB_HOST' => '127.0.0.1'],['DB_HOST' => '127.0.0.2']],
				*/						
			],
			
			'TPL'=> [
				'TPL_CACHE' => 'TPL_CACHE',				
			],
			
			'CACHE' => [
				'TPL_CACHE' => [
					'CACHE_TYPE' => 'FileCache',
					'CACHE_PATH' => $basePath . 'data/cache/',
					'GROUP' => 'tpl',
					'HASH_DEEP' => 0,
				],
				
				'DB_CACHE' => [
					'CACHE_TYPE' => 'FileCache',
					'CACHE_PATH' => $basePath . 'data/cache/',
					'GROUP' => 'db',
					'HASH_DEEP' => 2,
				],
			],			
		];
	}

	/** 加载配置文件
	 * @param $file
	 * @throws \Exception
	 */
	static public function loadConfig($file){
		if(!file_exists($file) ){
			throw new \Exception("Config file '{$file}' not found", 500); 
		}
		$config = include($file);
		foreach($config as $k=>$v){
			if( is_array($v) ){
				if( !isset(self::$config[$k]) ) self::$config[$k] = array();
				self::$config[$k] = array_merge((array)self::$config[$k], $config[$k]);
			}else{
				self::$config[$k] = $v;
			}
		}
	}
	
	/**
	 * 获取配置项
	 * @param  string $key 配置名
	 * @return mixed
	 */
	static public function get($key=NULL){
		if( empty($key) ) return self::$config;
		$arr = explode('.', $key);
		switch( count($arr) ){
			case 1 : 
				if( isset(self::$config[ $arr[0] ])) {
					return self::$config[ $arr[0] ];
				}
				break;
			case 2 : 
				if( isset(self::$config[ $arr[0] ][ $arr[1] ])) {
					return self::$config[ $arr[0] ][ $arr[1] ];
				}
				break;
			case 3 : 
				if( isset(self::$config[ $arr[0] ][ $arr[1] ][ $arr[2] ])) {
					return self::$config[ $arr[0] ][ $arr[1] ][ $arr[2] ];
				}
				break;						
			default: break;
		}
		return NULL;
	}

	/**
	 * 设置配置项
	 * @param $key   配置名
	 * @param $value 配置值
	 * @return bool
	 */
	static public function set($key, $value){
		$arr = explode('.', $key);
		switch( count($arr) ){
			case 1 : 
				self::$config[ $arr[0] ] = $value;
				break;
			case 2 : 
				self::$config[ $arr[0] ][ $arr[1] ] = $value;
				break;
			case 3 : 
				self::$config[ $arr[0] ][ $arr[1] ][ $arr[2] ] = $value;
				break;					
			default: return false;
		}
		return true;
	}
}